

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="前端代码的改造定义单例,创建 WebSocket 实例对象 创建 src&#x2F;utils&#x2F;socket_service.js 文件  定义单例 123456789101112export default class SocketService &amp;#123;  &#x2F;**   * 单例   *&#x2F;  static instance &#x3D; null  static get Instance() &amp;#123;">
<meta property="og:type" content="article">
<meta property="og:title" content="数据可视化项目九">
<meta property="og:url" content="http://example.com/2022/11/18/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E4%B9%9D/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="前端代码的改造定义单例,创建 WebSocket 实例对象 创建 src&#x2F;utils&#x2F;socket_service.js 文件  定义单例 123456789101112export default class SocketService &amp;#123;  &#x2F;**   * 单例   *&#x2F;  static instance &#x3D; null  static get Instance() &amp;#123;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-18T14:05:42.000Z">
<meta property="article:modified_time" content="2023-09-05T13:21:06.508Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="echarts">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>数据可视化项目九 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="数据可视化项目九"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-18 22:05" pubdate>
          2022年11月18日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          38 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">数据可视化项目九</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="前端代码的改造"><a href="#前端代码的改造" class="headerlink" title="前端代码的改造"></a>前端代码的改造</h1><h2 id="定义单例-创建-WebSocket-实例对象"><a href="#定义单例-创建-WebSocket-实例对象" class="headerlink" title="定义单例,创建 WebSocket 实例对象"></a>定义单例,创建 WebSocket 实例对象</h2><ul>
<li><p>创建 <code>src/utils/socket_service.js</code> 文件</p>
</li>
<li><p>定义单例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SocketService</span> &#123;<br>  <span class="hljs-comment">/**</span><br><span class="hljs-comment">   * 单例</span><br><span class="hljs-comment">   */</span><br>  <span class="hljs-keyword">static</span> instance = <span class="hljs-literal">null</span><br>  <span class="hljs-keyword">static</span> <span class="hljs-keyword">get</span> <span class="hljs-title function_">Instance</span>() &#123;<br>    <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-property">instance</span>) &#123;<br>      <span class="hljs-variable language_">this</span>.<span class="hljs-property">instance</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SocketService</span>()<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">instance</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="监听-WebSocket-事件"><a href="#监听-WebSocket-事件" class="headerlink" title="监听 WebSocket 事件"></a>监听 WebSocket 事件</h2><ul>
<li><p>定义 connect 函数,将创建的 <code>WebSocket</code> 赋值给实例属性</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SocketService</span> &#123;<br>......<br><span class="hljs-comment">// 实例属性</span><br>ws = <span class="hljs-literal">null</span><br><span class="hljs-comment">// 初始化连接websocket</span><br>connect () &#123;<br><span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">window</span>.<span class="hljs-property">WebSocket</span>) &#123;<br><span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;您的浏览器不支持 WebSocket!&#x27;</span>)<br>&#125;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>(<span class="hljs-string">&#x27;ws://localhost:9998&#x27;</span>)<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>监听事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js">connect () &#123;<br><span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">window</span>.<span class="hljs-property">WebSocket</span>) &#123;<br><span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;您的浏览器不支持 WebSocket!&#x27;</span>)<br>&#125;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>(<span class="hljs-string">&#x27;ws://localhost:9998&#x27;</span>)<br><span class="hljs-comment">// 监听连接成功</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onopen</span> = <span class="hljs-function">() =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;WebSocket 连接成功&#x27;</span>)<br>&#125;<br><span class="hljs-comment">// 1.服务器连接不成功 2.服务器关闭了连接</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onclose</span> = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;服务器关闭了连接&#x27;</span>)<br>&#125;<br><span class="hljs-comment">// 监听接收消息</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-function"><span class="hljs-params">msg</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;WebSocket 接收到数据&#x27;</span>)<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="定义注册函数"><a href="#定义注册函数" class="headerlink" title="定义注册函数"></a>定义注册函数</h2><p>记录一下当得到数据时, 应该调用的函数回调</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SocketService</span> &#123;<br>  <span class="hljs-comment">// 业务类型和回调函数的对于关系</span><br>  callBackMapping = &#123;&#125;<br>  <span class="hljs-comment">/**</span><br><span class="hljs-comment">   * socketType</span><br><span class="hljs-comment">   * trendData sellerData mapData rankData hotData stockData</span><br><span class="hljs-comment">   * fullScreen</span><br><span class="hljs-comment">   * themeChange</span><br><span class="hljs-comment">   * callBack</span><br><span class="hljs-comment">   * 回调函数</span><br><span class="hljs-comment">   */</span><br>  <span class="hljs-title function_">registerCallBack</span>(<span class="hljs-params">socketType, callBack</span>) &#123;<br>    <span class="hljs-comment">// 往 callBackMap中存放回调函数</span><br>    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callBackMapping</span>[socketType] = callBack<br>  &#125;<br>  <span class="hljs-title function_">unRegisterCallBack</span>(<span class="hljs-params">socketType</span>) &#123;<br>    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callBackMapping</span>[socketType] = <span class="hljs-literal">null</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="连接服务端"><a href="#连接服务端" class="headerlink" title="连接服务端"></a>连接服务端</h2><ul>
<li><p>在 main.js 中连接服务器端</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">SocketService</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/utils/socket_service&#x27;</span><br><span class="hljs-title class_">SocketService</span>.<span class="hljs-property">Instance</span>.<span class="hljs-title function_">connect</span>()<br></code></pre></td></tr></table></figure></li>
<li><p>将 SocketService 实例对象挂载到 Vue 的原型对象上</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Vue</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">$socket</span> = <span class="hljs-title class_">SocketService</span>.<span class="hljs-property">Instance</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="发送数据给服务端"><a href="#发送数据给服务端" class="headerlink" title="发送数据给服务端"></a>发送数据给服务端</h2><ul>
<li><p>在 socket_service.js 中定义发送数据的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SocketService</span> &#123;<br>......<br>send (data) &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;发送数据给服务器:&#x27;</span>)<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data))<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>先对修改 Trend.vue 进行代码改造</p>
<ul>
<li><p>created 中注册回调函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">created () &#123;<br><span class="hljs-comment">// 当socket来数据的时候, 会调用getData这个函数</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">registerCallBack</span>(<span class="hljs-string">&#x27;trendData&#x27;</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">getData</span>)<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>destroyed 中取消注册</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js">destroyed () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">unRegisterCallBack</span>(<span class="hljs-string">&#x27;trendData&#x27;</span>)<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>mounted 中往 socket 发送数据, 目的是想让服务端传输销量趋势这个模块的数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js">mounted () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-title function_">initChart</span>()<br><span class="hljs-comment">// this.getData() 先将getData的调用注释起来</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">send</span>(&#123;<br><span class="hljs-attr">action</span>: <span class="hljs-string">&#x27;getData&#x27;</span>,<br><span class="hljs-attr">socketType</span>: <span class="hljs-string">&#x27;trendData&#x27;</span>,<br><span class="hljs-attr">chartName</span>: <span class="hljs-string">&#x27;trend&#x27;</span><br>&#125;)<br>......<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>运行代码, 发现数据发不出去</p>
<p>因为在刷新界面之后, 客户端和服务端的连接并不会立马连接成功, 在处于连接状态下就调用 send 是发送不成功的, 因此需要修改 service_socket.js 中的 send 方法进行容错处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 是否已经连接成功</span><br>connected = <span class="hljs-literal">false</span><br>sendRetryCount = <span class="hljs-number">0</span><br>send (data) &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;发送数据给服务器:&#x27;</span>)<br><span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">connected</span>) &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">sendRetryCount</span> = <span class="hljs-number">0</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data))<br>&#125; <span class="hljs-keyword">else</span> &#123;<br><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">sendRetryCount</span>++<br><span class="hljs-variable language_">this</span>.<span class="hljs-title function_">send</span>(data)<br>&#125;, <span class="hljs-number">200</span> * <span class="hljs-variable language_">this</span>.<span class="hljs-property">sendRetryCount</span>) <span class="hljs-comment">// 发送数据尝试的次数越大, 则下一次连接的</span><br>延迟也就越长<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在 onopen 时设置 connected 的值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js">connect () &#123;<br>......<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onopen</span> = <span class="hljs-function">() =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;WebSocket 连接成功&#x27;</span>)<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">connected</span> = <span class="hljs-literal">true</span><br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>在 socket_service.js 中修改接收到消息的代码处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js">connect () &#123;<br><span class="hljs-comment">// 监听接收消息</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-function"><span class="hljs-params">msg</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;WebSocket 接收到数据&#x27;</span>)<br><span class="hljs-keyword">const</span> recvData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(msg.<span class="hljs-property">data</span>) <span class="hljs-comment">// 取出服务端传递的数据</span><br><span class="hljs-keyword">const</span> socketType = recvData.<span class="hljs-property">socketType</span> <span class="hljs-comment">// 取出业务类型,要根据业务类</span><br>型,得到回调函数<br><span class="hljs-comment">// 先判断有没有回调函数</span><br><span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">callBackMapping</span>[socketType]) &#123;<br><span class="hljs-keyword">if</span> (recvData.<span class="hljs-property">action</span> === <span class="hljs-string">&#x27;getData&#x27;</span>) &#123;<br><span class="hljs-keyword">const</span> realData = recvData.<span class="hljs-property">data</span> <span class="hljs-comment">// 得到该图表的数据</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">callBackMapping</span>[socketType].<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>,<br><span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(realData))<br>&#125;<br>&#125;<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<h2 id="断开重连机制"><a href="#断开重连机制" class="headerlink" title="断开重连机制"></a>断开重连机制</h2><p>如果初始化连接服务端不成功, 或者连接成功了, 后来服务器关闭了, 这两种情况都会触发 onclose 事件, 我们需要在这个事件中,进行重连</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js">connectRetryCount = <span class="hljs-number">0</span> <span class="hljs-comment">// 重连次数, 重连次数越大, 下一次再发起重连的延时也就越长</span><br>connect () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onopen</span> = <span class="hljs-function">() =&gt;</span> &#123;<br>......<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">connectRetryCount</span> = <span class="hljs-number">0</span> <span class="hljs-comment">// 连接成功之后, 重置重连次数</span><br>&#125;<br>......<br><span class="hljs-comment">// 1.服务器连接不成功 2.服务器关闭了连接</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">ws</span>.<span class="hljs-property">onclose</span> = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;服务器关闭了连接&#x27;</span>)<br><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">connectRetryCount</span>++<br><span class="hljs-variable language_">this</span>.<span class="hljs-title function_">connect</span>()<br>&#125;, <span class="hljs-number">200</span> * <span class="hljs-variable language_">this</span>.<span class="hljs-property">connectRetryCount</span>)<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="其他模块的修改"><a href="#其他模块的修改" class="headerlink" title="其他模块的修改"></a>其他模块的修改</h2><p>参照 Trend.vue , 其他图表要得到数据, 需要做这么几件事情</p>
<ul>
<li><p>created 中注册回调函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">created () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">registerCallBack</span>(<span class="hljs-string">&#x27;xxx&#x27;</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">getData</span>)<br><span class="hljs-comment">// xxx的可选值有: trendData,sellerData,mapData,rankData,hotData,stockData</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>destroyed 中取消注册</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">destroyed () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">unRegisterCallBack</span>(<span class="hljs-string">&#x27;xxx&#x27;</span>)<br><span class="hljs-comment">// xxx的值与注册时对应即可</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>mounted 中注释 getData 的调用,改成往 socket 发送数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js">mounted () &#123;<br><span class="hljs-variable language_">this</span>.<span class="hljs-title function_">initChart</span>()<br><span class="hljs-comment">// this.getData() 先将getData的调用注释起来</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$socket</span>.<span class="hljs-title function_">send</span>(&#123;<br><span class="hljs-attr">action</span>: <span class="hljs-string">&#x27;getData&#x27;</span>,<br><span class="hljs-attr">socketType</span>: <span class="hljs-string">&#x27;trendData&#x27;</span>,<br><span class="hljs-attr">chartName</span>: <span class="hljs-string">&#x27;trend&#x27;</span><br>&#125;)<br>......<br>&#125;,<br><span class="hljs-comment">// action的值不变,都是getData</span><br><span class="hljs-comment">// socketType的可选值</span><br>有:trendData,sellerData,mapData,rankData,hotData,stockData<br><span class="hljs-comment">// chartName的可选值有: trend,seller,map,rank,hot,stock</span><br></code></pre></td></tr></table></figure></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE/" class="category-chain-item">数据可视化项目</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/echarts/">#echarts</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>数据可视化项目九</div>
      <div>http://example.com/2022/11/18/数据可视化项目九/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月18日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/11/19/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E5%8D%81/" title="数据可视化项目十">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">数据可视化项目十</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/11/17/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E5%85%AB/" title="数据可视化项目七">
                        <span class="hidden-mobile">数据可视化项目七</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
